﻿using AutoMapper;
using DocumentFormat.OpenXml.EMMA;
using MediatR;
using Microsoft.Data.SqlClient;
using SmartProduction.Domain;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Write.API.Application.Commands.BomCommand;
using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Transactions;
using WorkflowCore.Services;

namespace SmartProduction.Write.API.Application.CommandHandlers.BomCommandHandler
{
    /// <summary>
    /// 处理添加BOM的命令请求
    /// </summary>
    public class BomCreateCommandHandler : IRequestHandler<BomCreateCommand, APIResult<Object>>
    {
        /// <summary>
        /// bom仓储
        /// </summary>
        private readonly IBaseRepository<Bom> bomRepository;
        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;
        private readonly IConfiguration configuration;
        /// <summary>
        /// 操作记录表
        /// </summary>
        private readonly IBaseRepository<OperationRecord> recordRepository;
        private readonly IBaseRepository<BomParts> partsRepository;
        private readonly DataDbContext db;
        private readonly IBaseRepository<ProcessInfo> processRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="bomRepository">bom仓储</param>
        /// <param name="mapper">映射</param>
        public BomCreateCommandHandler(IBaseRepository<Bom> bomRepository, IMapper mapper,IConfiguration configuration,IBaseRepository<OperationRecord> recordRepository,IBaseRepository<BomParts> partsRepository,DataDbContext db,IBaseRepository<ProcessInfo> processRepository)
        {
            this.bomRepository = bomRepository;
            this.mapper = mapper;
            this.configuration = configuration;
            this.recordRepository = recordRepository;
            this.partsRepository = partsRepository;
            this.db = db;
            this.processRepository = processRepository;
        }
       /// <summary>
/// 处理
/// </summary>
/// <param name="request">请求</param>
/// <param name="cancellationToken">重置</param>
/// <returns>返回受影响行数</returns>
public async Task<APIResult<object>> Handle(BomCreateCommand request, CancellationToken cancellationToken)
{
            APIResult<object> result = new APIResult<object>();
            using (var transaction = await db.Database.BeginTransactionAsync(cancellationToken))
    {
        try
        {
           
            Bom bom = new Bom();
            bom.BomNode = "BOM000001";
            int num = 1;
                    var temp = bomRepository.GetAll().Result.OrderByDescending(x => x.BomNode).FirstOrDefault();
                    if (temp != null)
            {
                num = Convert.ToInt32(temp.BomNode.Replace("BOM", ""));
                num++;
            }
            bom.BomNode = "BOM" + num.ToString().PadLeft(5, '0');

            bom.Bomtitle = request.Bomtitle;
            bom.DefaultBom = request.DefaultBom;
            bom.Version = request.Version;
            bom.FinishedType = request.FinishedType;
            bom.FinishedName = request.FinishedName;
            bom.DailyProduction = request.DailyProduction;
            bom.EstimatedCost = request.EstimatedCost;
            bom.CurrentInventory = request.CurrentInventory;
            bom.Notes = request.Notes;
            bom.CreatedBy = 1;
            bom.CreatedTime = DateTime.Now;

            var add1 = await bomRepository.AddAsync(bom);
                    if (add1 > 0)
                    {
                        request.parts.ForEach(c =>
                        {
                            c.BomId = bom.BomId;
                            c.PartsCode = "BM" + DateTime.Now.ToString("yyyyMMdd");
                            c.Inventory = 5;
                            c.AvailableProduce = 5;
                        });
                        request.process.ForEach(c =>
                        {
                            c.BomId = bom.BomId;
                            c.ProcessCode = "GX" + DateTime.Now.ToString("yyyyMMdd");
                        });
                        //添加物料
                        int add2 = await partsRepository.AddRanges(request.parts);
                        //添加工艺流程
                        int add3 = await processRepository.AddRanges(request.process);

                        result.Code = APIEnums.添加成功;
                        result.Msg = APIEnums.添加成功.ToString();
                        OperationRecord operationRecord = new OperationRecord()
                        {
                            BomId = bom.BomId, 
                            OperationName = "admin",
                            OperationDate = DateTime.Now,
                            OperationInfo = "新增"
                        };
                        int add4 = await recordRepository.AddAsync(operationRecord);
                        //提交事务
                        await transaction.CommitAsync(cancellationToken);
                    }
                    else
                    {
                        result.Code = APIEnums.添加失败;
                        result.Msg = APIEnums.添加失败.ToString();
                        //回滚事务
                        await transaction.RollbackAsync(cancellationToken);
                    }
                    return await Task.FromResult(result);
                }
                catch (Exception ex)
                {
                    // 输出详细的错误信息
                    string errorMessage = $"添加失败: {ex.Message}";
                    if (ex.InnerException != null)
                    {
                        errorMessage += $" 内部异常: {ex.InnerException.Message}";
                    }
                   
                    await transaction.RollbackAsync(cancellationToken);
                }

            }
            return result;
        }
    }
}